import { changePassword } from './../api/worksheets/index';
import { reactive } from 'vue';
import { defineStore } from 'pinia'
import { Result } from '@/utils/request';
import { loginTS, verificationTS } from '@/api/login/type';
import { getCaptchaLogin, getNewToken, getPermissionsList, getQuitLogin, getUserLogin, reading } from '@/api/login';
import { getToken, getRefreshToken, setToken, setRefreshToken, setIsLogin, removeIsLogin, removeToken, removeRefreshToken, cleanStorage } from '@/utils/storage'

export const useUserStore = defineStore('user', () => {

    const AppState = reactive({
        mobile_access_token: getToken() || '',
        mobile_refresh_token: getRefreshToken() || '',
        userName: '', // 用户名
        userId: '', // 用户id
        sidebarRouters: [],
    })

    const loading = ref(false)

    const readShow = ref()

    const tabActive = ref('/menu/worksheets')

    const searchName = ref('')//搜索内容

    const userName = ref('')

    const passWord= ref('')

    //验证码
    const captchaCode=ref('')

    // 登录
    const getLogin = async function (payload: loginTS) {
        try {

            const res = await getUserLogin(payload)

            if (res.data.token && res.data.refreshToken) {

                AppState.mobile_access_token = res.data.token

                AppState.mobile_refresh_token = res.data.refreshToken

                setToken(AppState.mobile_access_token)

                setRefreshToken(AppState.mobile_refresh_token)

                localStorage.setItem('mobile_userType', res.data.userType as string)

                localStorage.setItem('mobile_department', res.data.department as string)
            } else {
                setIsLogin(payload.username)
            }
            return res
        } catch (err) {
            //
        }
    }


    // 验证码登录
    const getLoginverification = async function (payload: verificationTS) {
        try {

            const res = await getCaptchaLogin(payload)

            if (res.data.token && res.data.refreshToken) {

                AppState.mobile_access_token = res.data.token

                AppState.mobile_refresh_token = res.data.refreshToken

                localStorage.setItem('mobile_userType', res.data.userType as string)

                localStorage.setItem('mobile_department', res.data.department as string)

                setToken(AppState.mobile_access_token)

                setRefreshToken(AppState.mobile_refresh_token)

                removeIsLogin()
            }

            return res
        } catch (err) {
            //
        }
    }

    // 无感刷新获取新的token
    const getNewAccessToken = async (): Promise<Result> => {
        const res: any = await getNewToken()
        if (res && res.statusCode === 200) {

            AppState.mobile_access_token = res.data.token

            AppState.mobile_refresh_token = res.data.refreshToken

            setToken(AppState.mobile_access_token)

            setRefreshToken(AppState.mobile_refresh_token)
        } else {
            removeToken()

            removeRefreshToken()
        }

        return res
    }

    // 退出
    const logOut = async () => {
        try {
            await getQuitLogin({ refresh_token: getRefreshToken() })

            AppState.mobile_access_token = ''

            AppState.mobile_refresh_token = ''

            sessionStorage.removeItem('lang')

            cleanStorage()
        } catch (error) {
            //
        }
    }

    //获取菜单权限
    const getPermission = async () => {
        const res: any = await getPermissionsList()

        const { username, menu_tree, user_id } = res

        AppState.userName = username

        AppState.userId = user_id

        AppState.sidebarRouters = menu_tree
    }

    // 读取
    const getReading = async (type: boolean, name: string) => {
        try {
            const res: any = await reading({
                is_flag: type,
                username: name
            })

            if (res.statusCode === 200) {
                readShow.value = res.is_agree
            }
        } catch (error) {
            //
        }
    }

    return {
        AppState,
        getLogin,
        getLoginverification,
        getNewAccessToken,
        logOut,
        loading,
        getPermission,
        tabActive,
        searchName,
        getReading,
        readShow,
        userName,
        passWord,
        captchaCode
    };
}, {
    persist: {
        enabled: true,

    }
});